//
//  GoodsDetailCtr.swift
//  smosky
//
//  Created by zhu xietong on 2018/5/21.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import soapp
import AsyncDisplayKit
import Eelay
import RTRootNavigationController
// import mosdks

public enum ShopContentMode:String {
    case info = "info"
    case comment = "comment"
    case rule = "rule"
    static var segbar:[[String:String]]{
        get{
            let datas = [
                ["name":"商品详情".loc,FK.selected:FK.YES,"id":"info"],
                ["name":"用户评论".loc,"id":"comment"]
            ]
            return datas
        }
    }
    
    static var segbar1:[[String:String]]{
        get{
            let datas = [
                ["name":"商品详情".loc,FK.selected:FK.YES,"id":"info"],
                ["name":"用户评论".loc,"id":"comment"],
                ["name":"退换货政策".loc,"id":"rule"]
            ]
            return datas
        }
    }
}

public class GoodsWebNode: WebCellNode {
    
    public override func replace(_ tag: String) -> String {
        return webModel["__model.content",""]
    }
    
    public override func loadWeb(model: NSMutableDictionary) {
        let urlStr = model["__model.contentdetail",""]
        view.backgroundColor = .clear

        if urlStr.len > 0{
            if let url = URL(string: urlStr)
            {
                let req = URLRequest(url: url)
                eeWebView.webView.load(req)
            }
  
        }
        else{
            let path = Bundle.path(for: GoodsWebNode.self, bundleName: "template", fileName: "商品图文", type: "html")
            
//                let path = Bundle.path(for: GoodsWebNode.self, bundleName: "template", fileName: "商品图文", type: "html")
//
            let render = TagsRender(templatePath: path!, model: 0)
            let media_path = Bundle.main.path(forResource: "html", ofType: nil)
            render.mediaBundlePath = media_path
//            render.css_names = ["css/app"]
            render.delegate = eeWebView
            eeWebView.defaultRender = render
            eeWebView.webView.load(render: eeWebView.render)
            
        }
//        print("____|\(eeWebView.webView.subviews)")
       
        

        //                let urlStr = "\(_SURL.host)/index/Webview/goodsdetail.html?id=\(goodsID)"
        //                    webNode.containner?.webView.load(render: render)
        //                if let url = URL(string: mo.detail["content_url",""])
        //                {
        //                let urlStr1 = "http://firstvar.com/demo/myprofile"
        
    }
    
    
}


public struct UIKeyMap {
    public let spec_current_price_node = ""
}

open class GoodsDetailCtr: NavChangeASListController{
    var scheme = SaleScheme.normal

    
    public let detailWebView = EeWebView()    
    open var contentMode:ShopContentMode = .info{
        didSet{
            tableNode.scrollToRow(at: IndexPath(row: 0, section: 0), at: .bottom, animated: true)
            weak var wself = self
            let sec3 = section3
            co_delay(delay: 0.25) {
                wself?.tableNode.model["section3"] = sec3
                //            tableNode.reloadData()
                //            print("++++++D|\(tableNode.model)")
                wself?.tableNode.reloadSections(IndexSet(integer: 3), with: .fade)
            }
        }
    }
    
    open var comments:NSMutableArray{
        get{
            
            let list = DataNode.path(node: "comments", mo.detail, value: NSMutableArray())
            list.list { (dict:NSMutableDictionary, i) in
                dict["cellID"] = "comment"
            }
            return list
        }
    }
    
    
    open var section3:NSMutableArray{
        get{
            switch contentMode {
            case .rule:
                return NSMutableArray()
            case .info:
                
                return websection.mutable_array
                //                return [
                //                    ["cellID":"web","__height__":webContainer.frame.size.height]
                ////                    ["img":__goods.one_str,"title":__goodsNames.one_str,"name":"goods1"],
                ////                    ["img":__goods.one_str,"title":__goodsNames.one_str,"name":"goods1"],
                ////                    ["img":__goods.one_str,"title":__goodsNames.one_str,"name":"goods1"],
            //                ].mutable_array
            case .comment:
                let cms = comments.mutable_array
                if self.comments.count > 0{
                    cms.add(["cellID":"moreComment","__model":mo.detail].mutable_dictionary)
                }
                else{
                    cms.add(["cellID":"emptyComment"].mutable_dictionary)
                }
                return cms
            }
        }
    }
    
    open var websection:[[String:Any]]{
        get{
            //            var conent = "<div>\(mo.detail["content",""])</div>"
            //            conent.replaceAll(matching: "<span\\s*.*?[^/]>", with: "")
            //            conent.replaceAll(matching: "</span>", with: "")
            //            let __elemet = EeXMLParser.scan(xmlString: conent)
            var list = [[String:Any]]()
            //            list.append(["cellID":"__blank"])
            //            if let element = __elemet
            //            {
            //                let items = element.displayTags
            //                for one in items
            //                {
            //                    list.append(one)
            //                }
            //            }
            //            list.append(["cellID":"__blank"])
            list.append(["cellID":"web","reuseID":"detail","__model":mo.detail])
            return list
        }
    }
    
    open var sections: TP.section{
        get{
            let sec:TP.section = [
                [
                    ["cellID":"info","__model":mo.detail],
                    ["cellID":"server","__model":mo.detail],
                ],
                [],
                [],
                section3 as! Array<[String : Any]>,
                [
                    ["cellID":"__blank"],
                    ["cellID":"recGoods",
                     "list":[
                        //                            ["img":__images.one_str,"title":__titles.one_str],
                        //                            ["img":__images.one_str,"title":__titles.one_str],
                        //                            ["img":__images.one_str,"title":__titles.one_str],
                        ]
                    ],
                ]
            ]
            return sec
        }
    }
    open var selector: TP.selector{
        
        get{
            let sel:TP.selector = [
                "cellID<info>":InfoCell.self,
                "cellID<server>":ServerCell.self,
                "cellID<web>":GoodsWebNode.self,
                "cellID<comment>":CommentCell.self,
                "cellID<emptyComment>":EmptyCommentCell.self,
                "cellID<moreComment>":MoreCommentCell.self,
                "cellID<recGoods>":RecItemCell.self,
                "cellID<__blank>":WhiteCell.self,
                "tagName<img>":ImageCell.self,
                "<section2>":TextNodeCell.self,
                ]
            return sel
        }
    }
    
    public var __header:CoversView? = nil
    open var header:CoversView{
        get{
            if let hd = __header{
                return hd
            }
            let hd = CoversView(frame:  CGRect(x: 0, y: 0, width: Swidth, height: (Swidth-TP.topHeight)))
            hd.mo.controller = self
            
            __header = hd
            return hd
        }
    }
    
    
    
    public var goodsID:String{
        get{
            //            print("++++UUU--===|\(mo.model)")
            var id = mo.model["goodsid",""]
            if id.len < 1
            {
                id = mo.model["id",""]
            }
            return id
        }
    }
    
    public var __bottomBar:EeBottomBar? = nil
    open var bottomBar:EeBottomBar{
        get{
            if let bar = __bottomBar{
                return bar
            }else{
                let bar = initBottomBar()
                __bottomBar = bar
                return bar
            }
        }
        set{
            __bottomBar = newValue
        }
    }
    
    open func initBottomBar()->EeBottomBar{
        return BuyBar()
    }
    
    public let cartBt = UIButton(frame: [26,26])
    public let shareBt = UIButton(frame: [26,26])

    override open func layTable(tableView: UIView) {
        jo_contentView.eelay = [
            [tableView,[ee.T.L.R],[bottomBar,ee.T,ee.B]],
            [bottomBar,[ee.L.B.R]],
        ]
        bottomBar.controller = self
    }
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        tableNode.view.backgroundColor = UIColor._background
        
        title = "详情".loc
        tableNode.view.separatorStyle = .none
        //        tableNode.view.buildDynamicHeight()
        
        bar.changeMode = {[weak self] mode in
            self?.contentMode = mode
        }
        
        buildBackBtChangeNavSupport()
        navChangeOffsetY = Swidth - TP.topHeight
        mo_request_send()
        rt_disableInteractivePop = false

        //        self.navigationItem.rightBarButtonItem =
        
    }
    
     override open func buildRightChangeNavSupport() {
    //        let back_icon = UIImage(named: "nav_back_normal")?.rt_tintedImage(with: self.notranpresentTopStyle.navBarTintColor)

            
//            backBt.setImage(UIImage(named: "nav_back_shadow"), for: .normal)
//            self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBt)
//            backBt.addTarget(self, action: #selector(bkButtonPress), for: .touchUpInside)
//
//            cartBt.setImage(UIImage(named: "gouwuche_02"), for: .normal)
//            self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: cartBt)
//            cartBt.addTarget(self, action: #selector(showMyCart), for: .touchUpInside)

        }
    
    override open func buildBackBtChangeNavSupport() {
//        let back_icon = UIImage(named: "nav_back_normal")?.rt_tintedImage(with: self.notranpresentTopStyle.navBarTintColor)
        
        backBt.setImage(UIImage(named: "back-indicator-shadow"), for: .normal)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBt)
        backBt.addTarget(self, action: #selector(bkButtonPress), for: .touchUpInside)
        
        
        cartBt.setImage(UIImage(named: "gouwuche_02"), for: .normal)
        
        shareBt.setImage(UIImage(named: "share-shadow"), for: .normal)

        
        self.navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: cartBt),UIBarButtonItem(customView: shareBt)]
        cartBt.addTarget(self, action: #selector(showMyCart), for: .touchUpInside)
        shareBt.addTarget(self, action: #selector(doShare), for: .touchUpInside)

        rt_disableInteractivePop = false

    }
    
    
    

    override open func updateNavTransparent(transparent:NavTransparent) {
        switch transparent {
        case .no:
            let back_icon = UIImage(named: "back-indicator")?.rt_tintedImage(with: self.notranpresentTopStyle.navTintColor)
            let cart_icon = UIImage(named: "gouwuche_01")?.rt_tintedImage(with: self.notranpresentTopStyle.navTintColor)
            let share_icon = UIImage(named: "share-tint")?.rt_tintedImage(with: self.notranpresentTopStyle.navTintColor)

            backBt.setImage(back_icon, for: .normal)
            cartBt.setImage(cart_icon, for: .normal)
            shareBt.setImage(share_icon, for: .normal)

        case .yes:
            backBt.setImage(UIImage(named: "back-indicator-shadow"), for: .normal)
            cartBt.setImage(UIImage(named: "gouwuche_02"), for: .normal)
            shareBt.setImage(UIImage(named: "share-shadow"), for: .normal)
        default:
            break
        }
    }
    
    @objc func showMyCart() {
//        var shareUrl = "https://www.probuyerglobal.com"
//        weak var wself = self
//        let qute:ShareQute = .init(
//                    title: "Probuyer 购物",
//                    icon:__images.one_str,
//                    link: shareUrl, image: nil, desc: nil)
//        
//        let share = MoShare().qute(qute).finish({ (success, msg, _, _) in
//        })
//        
//        share.show()
        weak var wself = self
        EeAuthControl.getUser { (ok, msg, user) in
            if ok{
                let ctr = ShoppingCartListCtr()
                wself?.navigationController?.pushViewController(ctr, animated: true)
            }
        }
    }
    
    
    @objc func doShare(){
        var shareUrl = mo.detail["share_url",""]
        weak var wself = self
        let qute:ShareQute = .init(
                    title:mo.detail["title",""],
                    icon:mo.detail["thumb",""],
                    link: shareUrl, image: nil, desc: nil)
    
        let share = MoShare().qute(qute).finish({ (success, msg, _, _) in
        })

        share.show()
    }
    
    open var detailURL:String{
        get{
            return _SURL.商品详情.url
        }
    }
    
    override open func mo_request_send() {
        
        weak var wself = self
        loadingV.loading()
        JoTask().get.log.params(["id":goodsID]).url(detailURL).log_response().json_handle { (status, msg, obj, resp) in
            wself?.loadingV.dismiss()
            if status.isSuccess{
                if let dict = obj as? NSMutableDictionary{
                    wself?.mo.detail = dict
                    return
                }
            }
            wself?.loadingV.show(message: msg, title: "")
        }.run()
    }
    
    func get_recommends() {
        
        weak var wself = self
        JoTask().get.log.params(["goodsid":goodsID])._surl(.商品推荐).json_handle { (status, msg, obj, resp) in
            if status.isSuccess{
                if let list = obj as? NSMutableArray{
                    if list.count > 0{
                        wself?.tableNode.model <-- ("section4.1.list",list,NodeInsert.arrayRefresh)
                        wself?.tableNode.reloadSections(IndexSet(integer: 4), with: .none)
                        return
                    }
                }
                wself?.tableNode.model <-- ("section4.1.cellID","__blank",NodeInsert.dictValue)
                wself?.tableNode.model <-- ("section4.1.__cell__","cellID<__blank>",NodeInsert.dictValue)
                wself?.tableNode.reloadSections(IndexSet(integer: 4), with: .none)
            }
        }.run()
    }
    
    
    
    var activeType:Goods.ActiveType = .none
    override open func mo_detail_reload() {
        
        Goods.ActiveType.markCellID(item: mo.detail)
        activeType = Goods.ActiveType(item: mo.detail)
        mo.detail["__scheme"] = scheme.rawValue
        self.tableNode.view.tableHeaderView  = header
        let imgs = DataNode.path(node: "thumbs", mo.detail, value: NSMutableArray())
        var covers = [[String:Any]]()
        imgs.list { (one:String, i) in
            covers.append(["img":one])
        }
        header.mo.model = [
            "id":"imgs",
            "__model":mo.detail,
            "options":covers,
        ].mutable_dictionary
        
        tableNode.load(sections: sections, selector: selector)
        bottomBar.mo.model = mo.detail
        willReloadData()
        tableNode.reloadData()
        get_recommends()
        //        loadRecommendGoods()
        
    }
    
    open func willReloadData() {
        
    }
    
    
    override open func scrollViewDidScroll(_ scrollView: UIScrollView) {
        super.scrollViewDidScroll(scrollView)
        if self.appearStatus != .didAppear
        {
            return
        }
        if let headerView = self.tableNode.view.tableHeaderView as? CoversView{
            headerView.scrollViewDidScroll(scrollView: scrollView)
        }
    }
    
    
//    override open func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode {
//        let node = super.tableNode(tableNode, nodeForRowAt: indexPath)
//        if let webNode = node as? GoodsWebNode{
//            
//            if webNode.eeWebView == nil
//            {
//                
//                webNode.eeWebView = self.detailWebView
//                let urlStr = mo.detail["contentdetail",""]
//                //                let urlStr = "\(_SURL.host)/index/Webview/goodsdetail.html?id=\(goodsID)"
//
//                //                    webNode.containner?.webView.load(render: render)
//                
//                //                if let url = URL(string: mo.detail["content_url",""])
//                //                {
////                let urlStr1 = "http://firstvar.com/demo/myprofile"
//                if let url = URL(string: urlStr)
//                {
//                    let req = URLRequest(url: url)
//                    webNode.eeWebView?.webView.load(req)
//                }
//            }
//        }
//        return node
//    }

    var bar:GoodsInfoModeBar = Segbar()
    open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 3{
            return bar
        }
        return nil
    }
    open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 3{
            return 40
        }
        return  0
    }
    
    
    override open func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
            switch actionID {
            case EeWebView.updateWebHeightKey:
//                let row = model[int:"__row__",0]
//                let section = model[int:"__section__",0]
//                let indexP = IndexPath(row: row, section: section)
//                tableNode.reloadRows(at: [indexP], with: .none)
//                IndexSet(integer: 2)
//                tableView.beginUpdates()
//                tableView.endUpdates()
                
//                weak var wself = self
//                tableNode.performBatchUpdates({
//                     wself?.tableNode.reloadSections(IndexSet(integer: 3), with: .fade)
//                }, completion: nil)
//                tableNode.reloadSections(IndexSet(integer: 3), with: .fade)
                break
            default:
                break
            }
    }
    
    deinit {
        //        print("++++++finish GoodsDetailCtr")
    }
}

extension GoodsDetailCtr
{
    
    
    public func replace(_ tag: String) -> String {
        //                    print("lllll000000|\(tag)")
        switch tag {
        case "name":
            return "商品详情".loc
        case "time":
            return Date()["yyyy-MM-dd HH:mm"]
        case "logo":
            return __heads.one_str
        case "content":
            var content = mo.detail["content",""]
            content.replaceAll(matching: "<img(.+?)src=\"(.+?)\"(.+?)>", with: "<img src=\"$2\"/>")//去掉img style 属性
            content.replaceAll(matching: "text-indent", with: "-text-indent")//图片对其存在的显示bug
            return content
        default:
            return ""
        }
    }
}







